﻿Ext.BLANK_IMAGE_URL = '/script/ext/resources/images/s.gif';
Ext.onReady(function () {
    //初始化快速提示
    Ext.QuickTips.init();
    var modelid = jQuery.query.get("modelid");
    //将提示显示在form属性旁边
    Ext.form.Field.prototype.msgTarget = "side";
    //创建根节点
    var DepmetTreeRoot = new Ext.tree.AsyncTreeNode({ text: '文件柜树', id: 'DepmetTreeRoot', expanded: true, leaf: false });
    //创建树面板
    var DepmetTree = new Ext.tree.TreePanel({
        loader: new Ext.tree.TreeLoader({ dataUrl: "server/StockRoom/StockRoomTypeTree.aspx" }),
        id: 'DepmetTree',
        region: 'west',
        width: 255,
        minSize: 255,
        maxSize: 500,
        margins: '5 0 5 5',
        cmargins: '5',
        bodyStyle: "padding:2px;",
        title: "物品分类",
        split: true,
        rootVisible: false,
        lines: true,
        autoScroll: true,
        animate: true,
        collapsible: true,
        containerScroll: true,
        tbar: [{ iconCls: 'icon-expand-all',
            tooltip: '全部展开',
            handler: function () { DepmetTreeRoot.expand(true); }
        }, { iconCls: 'icon-collapse-all',
            tooltip: '全部折叠',
            handler: function () { DepmetTreeRoot.collapse(true); }
        }, { iconCls: 'icon-add',
            text: "同级",
            tooltip: '添加同级',
            handler: function () {
                var selectNode = DepmetTree.getSelectionModel().getSelectedNode();
                DepmetAdd(DepmetTree, DepmetTreeRoot, selectNode, true);
            }
        }, { iconCls: 'icon-add',
            text: "子级",
            tooltip: '添加子集',
            handler: function () {
                var selectNode = DepmetTree.getSelectionModel().getSelectedNode();
                DepmetAdd(DepmetTree, DepmetTreeRoot, selectNode, false);
            }
        }, { iconCls: 'icon-edit',
            text: "编辑",
            tooltip: '编辑',
            handler: function () {
                var selectNode = DepmetTree.getSelectionModel().getSelectedNode();
                if (selectNode) {
                    Ext.Msg.prompt("编辑公司/部门", "请输入新公司/部门名称", function (btn, text) {
                        if (btn == "ok") {
                            if (text != "") {
                                Ext.Ajax.request({
                                    url: "server/StockRoom/StockRoomTypeAdd.aspx",
                                    method: 'POST',
                                    params: { text: text, nodeId: selectNode.id },
                                    success: function (response) {
                                        var json = Ext.util.JSON.decode(response.responseText);
                                        if (json.success) {
                                            Ext.Msg.alert("提示", json.msg);
                                            DepmetTree.loader.load(DepmetTreeRoot);
                                        } else {
                                            Ext.Msg.alert("错误", json.msg);
                                        }
                                    }
                                });
                            } else {
                                Ext.Msg.alert("提示", "请输入名称");
                            }
                        }
                    }, "", "", selectNode.text);
                }
            }
        }, { iconCls: 'icon-del',
            text: "删除",
            tooltip: '删除',
            handler: function () {
                var selectNode = DepmetTree.getSelectionModel().getSelectedNode();
                if (selectNode) {
                    Ext.Msg.confirm("确认提示", "确认要删除" + selectNode.text + "?", function (btn) {
                        if (btn == "yes") {
                            Ext.Ajax.request({
                                url: "server/StockRoom/StockRoomTypeDel.aspx",
                                method: 'POST',
                                params: { nodeId: selectNode.id },
                                success: function (response) {
                                    var json = Ext.util.JSON.decode(response.responseText);
                                    if (json.success) {
                                        Ext.Msg.alert("提示", json.msg);
                                        DepmetTree.loader.load(DepmetTreeRoot);
                                    } else {
                                        Ext.Msg.alert("错误", json.msg);
                                    }
                                }
                            });
                        }
                    }, "", "", selectNode.text);
                }
            }
        }]
    });
    DepmetTree.setRootNode(DepmetTreeRoot);
    DepmetTree.on('dblclick', function (node, e) {
        e.stopEvent();
        var model = DepmetTree.getSelectionModel();
        var selectNode = model.getSelectedNode();
        if (selectNode) {
            groupStore.load({ params: { start: 0, limit: pageSize, ClassId: selectNode.id} });
        }
    });
    DepmetTree.on('checkchange', function (node, checked) {
        selectParentNode(node, checked);
        selectChildNode(node, checked);
    }, DepmetTree);

    //定义数据模型
    var UserInfo = new Ext.data.Record.create([
                        { name: 'ID', type: 'int', mappging: "ID" },
                        { name: 'StockRoomName', type: 'string', mappging: "StockRoomName" },
                        { name: 'StockRoomCount', type: 'int', mappging: "StockRoomCount" },
                        { name: 'StockRoomRemark', type: 'string', mappging: "StockRoomRemark" },
                        { name: 'StockRoomPrice', mappging: "StockRoomPrice" },
                        { name: 'StockRoomTime', mappging: "StockRoomTime" },
                        { name: 'PurchaseType', type: 'string', mappging: "PurchaseType" }
                        ]);

    /*创建数据源*/
    var groupStore = new Ext.data.GroupingStore({
        proxy: new Ext.data.HttpProxy({ url: "server/StockRoom/StockRoomList.aspx" }),
        reader: new Ext.data.JsonReader({ totalProperty: "Count", root: "List" }, UserInfo),
        sortInfo: { field: 'ID', direction: 'DESC' }
    });
    //设置每页条数
    var pageSize = 20;
    var cookiePageSize = parseInt(Ext.util.Cookies.get("pageSize"));
    if (cookiePageSize) { pageSize = cookiePageSize; }
    //加载数据源
    groupStore.load({ params: { start: 0, limit: pageSize} });
    //创建选择列模型
    var sm = new Ext.grid.CheckboxSelectionModel();
    //定义列模型
    var cm = new Ext.grid.ColumnModel([
            sm,
            { id: 'ID', header: '编号', dataIndex: 'ID', width: 60, sortable: true },
            { id: 'StockRoomName', header: '物品名称', dataIndex: 'StockRoomName', width: 120, sortable: true },
            { id: 'StockRoomPrice', header: '物品价钱', dataIndex: 'StockRoomPrice', width: 80, sortable: true },
            { id: 'StockRoomCount', header: '物品数量', dataIndex: 'StockRoomCount', width: 80, sortable: true },
            { id: 'StockRoomTime', header: '入库时间', dataIndex: 'StockRoomTime', width: 150, sortable: true, renderer: Ext.util.Format.dateRenderer('Y-m-d'), format: "Y-m-d" }
            ]);

    //创建下[每页行数]拉框
    var comboBox = new Ext.form.ComboBox({
        width: 50,
        typeAhead: true,
        triggerAction: 'all',
        lazyRender: true,
        mode: 'local',
        title: "每页行数",
        emptyText: pageSize,
        store: new Ext.data.ArrayStore({
            id: 0,
            fields: ['myId', 'displayText'],
            data: [[10, 10], [20, 20], [30, 30], [50, 50], [100, 100]]
        }),
        valueField: 'myId',
        displayField: 'displayText'
    });
    comboBox.on("select", function (combo, record, index) {
        Ext.util.Cookies.set("pageSize", record.id);
        window.location.reload();
    });

    //            //定义备注
    //            var remark = new Ext.form.TextArea({
    //                fieldLabel: '备注', //标签名称 
    //                anchor: '100%',
    //                height: 140,
    //                name: "ContactsRemark"
    //            });

    //            //信息检索内容
    //            var form = new Ext.form.FormPanel({
    //                border: false,
    //                frame: true,
    //                labelAlign: "right",
    //                buttonAlign: "right",
    //                labelWidth: 100,
    //                items: [new Ext.form.TextField({
    //                    allowBlank: false,
    //                    fieldLabel: '请输入姓名查询',
    //                    labelStyle: 'color:red',
    //                    name: 'Name', //
    //                    blankText: '姓名不能为空',
    //                    anchor: '100%'
    //                })]
    //            });
    //            //信息检索窗口
    //            var win2 = new Ext.Window({
    //                border: false,
    //                width: 400,
    //                title: "信息检索",
    //                width: 640,
    //                items: form,
    //                iconCls: 'icon-search-16',
    //                buttonAlign: "center",
    //                buttons: [{
    //                    iconCls: 'icon-search-16',
    //                    text: "开始检索",
    //                    handler: function () {
    //                        if (form.form.isValid()) {
    //                            var key = form.getForm().findField("Name").getValue();
    //                            groupStore.load({ params: { key: key, start: 0, limit: pageSize} });
    //                        }
    //                    }
    //                }, {
    //                    text: "重置表单",
    //                    handler: function () { form.getForm().reset(); }
    //                }],
    //                closeAction: "hide"
    //            });

    var grid = new Ext.grid.GridPanel({
        title: "物品列表",
        store: groupStore,
        border: true,
        margins: '5 5 0 0',
        region: 'center',
        view: new Ext.grid.GroupingView(),
        sm: sm,
        cm: cm,
        tbar: [{
            iconCls: 'icon-add',
            text: '入库登记',
            value: 0,
            handler: function (btn) {
                UserForm.setTitle("入库登记");
                UserForm.getForm().reset();
                viewport.items.get(2).expand();
            }
        }, {
            ref: '../removeBtn',
            iconCls: 'icon-del',
            text: '删除',
            disabled: true,
            handler: function () {
                Ext.MessageBox.confirm("确认提示", "确认要删除所选行数据？", function (btn) {
                    if (btn == "yes") {
                        var s = grid.getSelectionModel().getSelections();
                        var delR = new Array();
                        var delRid = new Array();
                        for (var i = s.length - 1; i >= 0; i--) {
                            var r = s[i];
                            if (r.get('ID') != undefined) { delRid.push(r.get('ID')); delR.push(r); }
                        }
                        Ext.Ajax.request({
                            url: "server/StockRoom/StockRoomDel.aspx?modelid=" + modelid,
                            method: 'POST',
                            params: { id: delRid },
                            success: function (response) {
                                var json = Ext.util.JSON.decode(response.responseText);
                                if (json.success) {
                                    for (var i = 0; i < delR.length; i++) {
                                        if (json.ids.valueOf(delR[i].get('ID'))) { groupStore.remove(delR[i]) }
                                    }
                                    Ext.Msg.alert("提示", "已删除" + json.count + "行<br/>" + json.msg);
                                } else {
                                    Ext.Msg.alert("错误", json.msg);
                                }
                            }
                        });
                    }
                });
            }
        }, {
            ref: '../viewBtn',
            iconCls: 'icon-view',
            text: '查看',
            disabled: true,
            handler: function (btn) {
                var list = grid.getSelectionModel().getSelections();
                window.open("server/StockRoom/StockRoomDetail.aspx?id2=" + list[0].get("ID"));
            }
        }],
        bbar: new Ext.PagingToolbar({
            store: groupStore,
            pageSize: pageSize,
            displayInfo: true,
            prependButtons: true,
            items: ['每页行数', comboBox, '-'],
            displayMsg: "本页显示第{0}条到第{1}条数据，共{2}条",
            emptyMsg: "暂无记录"
        })
    });

    //采购物品类型定义
    //    var PurchaseTypeTree = new Ext.form.ComboBoxTree({
    //        name: "myDepmet",
    //        fieldLabel: "请选择",
    //        hiddenName: "PurchaseType",
    //        listEmptyText: "*暂无信息*",
    //        emptyText: "请选择",
    //        editable: false,
    //        resizable: true,
    //        tree: new Ext.tree.TreePanel({
    //            root: new Ext.tree.AsyncTreeNode({ text: '文件夹', id: '0', leaf: false }),
    //            lines: true,
    //            rootVisible: false,
    //            border: false,
    //            dataUrl: "server/StockRoom/StockRoomTypeTree.aspx"
    //            //,beforeload: function(n) { if (n) { this.getLoader().baseParams.id = n.attributes.id; } }
    //        })
    //    });

    var PurchaseTypeTree = new Ext.ux.ComboBoxTree({
        fieldLabel: "物品类别",
        hiddenName: "PurchaseType",
        name: "ParentID",
        width: 143,
        emptyText: "请选择",
        blankText: '物品类别不能为空',
        labelStyle: 'color:red',
        allowBlank: false,
        editable: false,
        selectNodeModel: 'all',
        tree: {
            xtype: 'treepanel',
            lines: true, rootVisible: false, border: false,
            loader: new Ext.tree.TreeLoader({ dataUrl: 'server/StockRoom/StockRoomTypeTree.aspx' }),
            root: new Ext.tree.AsyncTreeNode({ text: '选文件夹', id: "0", leaf: false })
        }
    });


    var UserForm = new Ext.form.FormPanel({
        region: 'south',
        title: "入库登记",
        margins: "0 5 5 0",
        collapsible: true,
        expanded: false,
        frame: true,
        split: false,
        height: 300,
        labelAlign: "right",
        labelWidth: 70,
        buttonAlign: "center",
        items: [{
            layout: 'column', //定义为列模式
            items: [{
                columnWidth: .2, //显示为第一列的宽度33%
                layout: 'form',
                items: [{
                    xtype: 'textfield',
                    name: "ID",
                    fieldLabel: "编号",
                    disabled: true
                }]
            }, {
                columnWidth: .2,
                layout: 'form',
                items: [{
                    xtype: 'textfield',
                    name: "StockRoomName",
                    blankText: '物品名称不能为空',
                    labelStyle: 'color:red',
                    allowBlank: false,
                    fieldLabel: "物品名称"
                }]
            }, {
                columnWidth: .2,
                layout: 'form',
                items: [{
                    xtype: 'textfield',
                    name: "StockRoomPrice",
                    blankText: '物品价格不能为空',
                    regex: /^[1-9]\d*$/,
                    regexText: "只能输入数字!",
                    allowBlank: false,
                    fieldLabel: "物品价格"
                }]
            }, {
                columnWidth: .2,
                layout: 'form',
                items: [{
                    xtype: 'textfield',
                    name: "StockRoomCount",
                    blankText: '物品数量不能为空',
                    regex: /^[1-9]\d*$/,
                    regexText: "只能输入数字!",
                    allowBlank: false,
                    fieldLabel: "物品数量"
                }]

            }, {
                columnWidth: .2,
                layout: 'form',
                items: PurchaseTypeTree
            }]
        }, new Ext.form.HtmlEditor({
            fieldLabel: '备注', //标签名称 
            anchor: '100%',
            height: 140,
            name: "StockRoomRemark"
        })],
        buttons: [
                { text: "确定", handler: function () {
                    if (UserForm.form.isValid()) {
                        var params = {
                            ID: UserForm.getForm().findField("ID").getValue(),
                            StockRoomName: UserForm.getForm().findField("StockRoomName").getValue(),
                            StockRoomCount: UserForm.getForm().findField("StockRoomCount").getValue(),
                            StockRoomRemark: UserForm.getForm().findField("StockRoomRemark").getValue(),
                            PurchaseType: PurchaseTypeTree.getCtValue(),
                            StockRoomPrice: UserForm.getForm().findField("StockRoomPrice").getValue()
                        };
                        Ext.Ajax.request({
                            url: "server/StockRoom/StockRoomRegister.aspx?modelid=" + modelid,
                            params: params,
                            success: function (response) {
                                var json = Ext.util.JSON.decode(response.responseText);
                                if (json.success) {
                                    Ext.Msg.alert("申请成功", json.msg, function () {
                                        groupStore.load({ params: { start: 0, limit: pageSize} });
                                    });
                                    form.getForm().reset();
                                } else {
                                    Ext.Msg.alert("错误", json.msg);
                                }
                            },
                            failure: function (response) { Ext.Msg.alert("请求失败", response.responseText); }
                        });
                    }
                }
                },
                { text: "重置", handler: function () { UserForm.getForm().reset(); } }
                ]
    });
    //创建页面布局
    var viewport = new Ext.Viewport({ layout: 'border', items: [DepmetTree, grid, UserForm] });
    viewport.items.get(2).collapse();
    //布局加载
    viewport.doLayout();
    //延时加载
    setTimeout(function () { Ext.get('loading').remove(); Ext.get('loading-mask').fadeOut({ remove: true }); }, 400);
    //有选择行启用删除按钮
    grid.getSelectionModel().on('selectionchange', function (sm) {
        grid.removeBtn.setDisabled(sm.getCount() < 1);
        grid.viewBtn.setDisabled(sm.getCount() < 1 || sm.getCount() > 1);
    });
    grid.on('rowdblclick', function (g, index, e) {
        viewport.items.get(2).expand();
        var r = g.getSelectionModel().getSelected();
        if (r != null) {
            UserForm.setTitle("编辑信息");
            UserForm.form.loadRecord(new UserInfo({ 'ID': r.get("ID"), 'StockRoomName': r.get("StockRoomName"), 'StockRoomCount': r.get("StockRoomCount"), 'StockRoomPrice': r.get("StockRoomPrice"), 'PurchaseType': GetStockRoomTypeName(r.get("PurchaseType")), 'StockRoomRemark': r.get("StockRoomRemark") }));
            PurchaseTypeTree.setCtValue(GetFoldersName(r.get("ParentID")), r.get("ParentID"));

            //        Ext.get('parent_id').dom.value = r.get("PurchaseType");
            UserForm.doLayout();
        }
    });
});